<?php

include_once("data/dao/BaseDAO.php");
include_once("application/collection/Collection.php");
include_once("application/user/UserUtils.php");
include_once("application/collection/CollectionUtils.php");
include("conf.php");

class CollectionDAO extends BaseDAO{
	
	
	/**
	 * gets the users collection of games from the database
	 * 
	 * @param $id
	 * @return Collection
	 */
	public function getCollection($id){
		
		if(!UserUtils::idMatchesLoggedInUser($id))
			throw new Exception("attempting to retrive a collection that is not owned" .
					" by the logged in user!");		
	
		if(!UserUtils::userExists($id))
			throw new Exception("attempting to query collection table for a user that" .
					" does not exist!");

		self::connect();
		$find = mysql_query("SELECT * FROM " . COLLECTION_TABLE . " WHERE user_id = '$id'");
		
		if(mysql_num_rows($find) == 0)
			return null;
					
		while($row = mysql_fetch_assoc($find)){
			$games = explode(",", $row['collection']);
			return new Collection($id, $games);
		}
	}
	
	public function updateCollection($games, $id){
		
		if(!UserUtils::idMatchesLoggedInUser($id))
			throw new Exception("attempting to update a collection that is not owned" .
					" by the logged in user!");		

		if(!is_string($games))
			throw new Exception("attempting to insert a non string value into table!");
			
		self::connect();
		
		// if user does not already have a collection, create one
		if(!CollectionUtils::userHasACollection($id)){
			$result = mysql_query("INSERT INTO " . COLLECTION_TABLE .
						" (user_id, collection) VALUES('$id', '$games')");
			return;
		}
				
		$result = mysql_query("UPDATE " . COLLECTION_TABLE . 
					" SET collection = '$games' " .
					"WHERE user_id = '$id'");
					
		if(CollectionUtils::collectionIsEmpty($id))
			$this->deleteCollection($id);
		
		if(!$result)
			throw new Exception("sql query failed when updating collection table");
	}
	
	public function deleteCollection($userId){
		
		self::connect();
		mysql_query("DELETE FROM " . COLLECTION_TABLE . " WHERE user_id = '$userId'");
	}
	
	public function getNumberOfCollectionsContainingGame($id){
		
		self::connect();
		$find = mysql_query("SELECT * FROM " . COLLECTION_TABLE . " WHERE " .
				"collection like '%$id%'");
				
		return mysql_num_rows($find);
	}
	
	public function getCollectionCount($gameId){
		
		self::connect();
		$find = mysql_query("SELECT COUNT(*) FROM " . COLLECTION_TABLE . " WHERE " .
				"collection like '%$gameId%'");
		
		while($row = mysql_fetch_array($find)){
			return $row[0];
		}
	}
	
	/**
	 * finds all of the users that have the given game in their 
	 * collection.
	 * 
	 * @param $games array of game id's
	 * @return array of arrays ('user_id' => value, 'collection' => value)
	 */
	public function findUsersThatHaveGameInCollection(array $games, $page = ""){

		Validate::notNull($games);

		// number of results to display per page
		$rowsPerPage = 20;

		if(!isset($page)){
			$page = 1;
		}

		$findQuery = "SELECT DISTINCT user_id, collection FROM " . COLLECTION_TABLE . " WHERE ";
		for($i=0; $i<count($games); $i++){
			$findQuery = $findQuery . "collection like '%$games[$i]%'";
			if($i<count($games) -1){
				$findQuery = $findQuery . " OR ";
			}	
		}

		self::connect();
		$find = mysql_query($findQuery);
		$numOfRows = mysql_num_rows($find);		

		// early exit if there are no matches
		if($numOfRows == 0)
			return;
			
			
		// calculate the last page number
		$lastPage = ceil($numOfRows / $rowsPerPage);
		// check page is within range
		if($page > $lastPage){
			$page = $lastPage;
		}
		if($page < 1){
			$page = 1;
		}

		$limit = ' LIMIT ' .($page - 1) * $rowsPerPage .',' .$rowsPerPage;
		// append limit to query
		$findQuery = $findQuery . $limit;
		// execute query with limit
		$find = mysql_query($findQuery);
		
		$friends = array();
		while($row = mysql_fetch_assoc($find)){
			array_push($friends, array('user_id' => $row['user_id'],
									   'collection' => $row['collection']));
		}		

		return new FriendsResultsView($friends, (int) $lastPage, $numOfRows);
	}
}

class FriendsResultsView{
	
	private $friends;
	private $totalPages;
	private $totalFriends;
	
	public function FriendsResultsView($friends, $totalPages, $totalFriends){
		
		$this->friends = $friends;
		$this->totalPages = $totalPages;
		$this->totalFriends = $totalFriends;
//		if($this->lastpage < 1){
//			$this->lastpage = 1;
//		}
	}
	
	public function getFriends(){
		return $this->friends;
	}
	
	public function getLastPage(){
		return $this->totalPages;
	}
	
	public function getTotalFriends(){
		return $this->totalFriends;
	}
}
?>
